var express = require('express');
var multer  = require('multer');//处理文件上传
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var session = require('express-session');
var SessionStore = require('express-mysql-session');
var dbConfig = require('./dbConfig');
var passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy;
var pass = require('./utils/pass');

var routes = require('./routes/index');

var circle = require('./routes/circle');

var users = require('./routes/users');
var debug = require('debug')('CarClubAdmin');
var fs = require('fs');

var ueditor = require("ueditor");

var app = express();

var options = {
    host: dbConfig.host,
    port: dbConfig.port,
    user: dbConfig.user,
    password: dbConfig.password,
    database: dbConfig.database,
    checkExpirationInterval: 7200000,//频繁过期会话将会被清除 ；毫秒为单位
    expiration: 7200000,//过期时间
    createDatabaseTable: true//创建表
}
var sessionStore = new SessionStore(options);


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use("/ueditor/ue", ueditor(path.join(__dirname, 'public'), function(req, res, next) {
    // ueditor 客户发起上传图片请求
    if(req.query.action === 'uploadimage'){
        var foo = req.ueditor;
        var imgname = req.ueditor.filename;

        var img_url = '/images/ueditor/';
        res.ue_up(img_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
    }
    //  客户端发起图片列表请求
    else if (req.query.action === 'listimage'){
        var dir_url = '/images/ueditor/';
        res.ue_list(dir_url);  // 客户端会列出 dir_url 目录下的所有图片
    }
    // 客户端发起其它请求
    else {

        res.setHeader('Content-Type', 'application/json');
        res.redirect('/ueditor/ueditor.config.json')
    }}));

app.use(multer({
    dest: './uploads/',
    limits: {
        fieldNameSize: 100,
        files: 1,
        fileSize: 2048*1024//最大上传2M图片
    }/*,
    onFileSizeLimit: function (file) {
        console.log('Failed: ', file.originalname);
        fs.unlink('./uploads/' + file.path) // delete the partially written file
    }*/
}));//处理文件上传



app.use(cookieParser('keyboard cat'));
app.use(express.static(path.join(__dirname, 'public')));
//app.use(session({secret: 'carClub_cookie', cookie: { maxAge: 60000 }}));
app.use(session({
    //key: 'session_cookie',
    secret: 'keyboard cat',
    store:sessionStore,//会话存储实例
    resave: true,
    saveUninitialized: true//"未初始化"将其保存到存储的会话
}));
/*app.use(express.static(path.join(__dirname, 'public')));*/
app.use(passport.initialize());
app.use(passport.session());

app.use(function (req, res, next) {
    var url = req.originalUrl;
    if(url.indexOf('login')>0&&req.isAuthenticated()){//已登录
        if(req.body.app){//如果手机app登录的直接返回user
            return res.send(JSON.stringify(req.session.passport.user));
        }else if(req.session.passport.user.usertype==2){
            return res.render('index1',{
                user:req.session.passport.user
            });
        }else{
            return res.render('index',{
                name:req.session.passport.user.username
            });
        }

    }else if(url.indexOf('auth')>0&&req.isAuthenticated()){//路径包含auth并且已经通过验证的用户往下执行
        return next();
    }else if(url.indexOf('auth')>0&&!req.isAuthenticated()){//未通过验证的去登录
        //res.redirect('/login');
        res.render('login',{
            msg:''
        });
    }else{//其它路径不验证
        return next();
    }

});

app.use('/', routes);//主要为生活服务类请求

app.use('/circle', circle);//圈子管理

app.use('/auth/users', users);//用户管理
app.post('/login',pass.postlogin);//登录认证
app.get('/logOut',pass.logout);//退出登录
// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    res.redirect('/404.html');
    //next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


app.set('port', process.env.PORT || 8100);
var server = app.listen(app.get('port'), function() {
    debug('--Server listening on port ' + server.address().port);
});

module.exports = app;
